library taro_api;

import 'dart:async';
import 'dart:convert';
import 'dart:core';
// ignore: avoid_web_libraries_in_flutter
import 'dart:js';
import 'dart:typed_data';

import 'package:flutter/widgets.dart';

part './base.dart';
part './router.dart';
part './ui.dart';
part './network.dart';

class TaroApi {
  static JsObject get global => context['Taro'];
  static _TaroBaseApi get base => _TaroBaseApi();
  static _TaroRouterApi get router => _TaroRouterApi();
  static _TaroUIApi get ui => _TaroUIApi();
  static _TaroNetworkApi get network => _TaroNetworkApi();

  static Future wrapPromise(JsObject value) {
    final completer = Completer();
    value
      ..callMethod(
        'then',
        [
          (value) {
            completer.complete(value);
          }
        ],
      )
      ..callMethod(
        'catch',
        [
          (value) {
            completer.completeError(value);
          }
        ],
      );
    return completer.future;
  }

  static JsObject jsify(Map values) {
    return JsObject.jsify(values..removeWhere((key, value) => value == null));
  }

  static Map jsonify(JsObject value) {
    if (value == null) return null;
    try {
      final jsonString =
          (context['JSON'] as JsObject).callMethod('stringify', [value]);
      return json.decode(jsonString);
    } catch (e) {
      return {};
    }
  }
}
